package com.hs.springboot_demo.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSON;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.hs.springboot_demo.common.Result;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.List;

/**
 * @author d-will
 * @create 2022--03--02 13:35
 */
@RestController
@RequestMapping("/file")
public class FileController {
	@Value("9090")
	private String port;

	private static final String ip = "http://localhost:";

	@PostMapping("/upload")
	public Result<?> upload(MultipartFile file) throws IOException {
		String originalFilename = file.getOriginalFilename();//获取源文件名称
		String flag = IdUtil.fastSimpleUUID();
		//获取上传路径
		String rootFilePath = System.getProperty("user.dir") + "/springboot/src/main/resources/files/" + flag + "-" + originalFilename;
		//写入路径
		FileUtil.writeBytes(file.getBytes(), rootFilePath);
		return Result.success(ip + port + "/file/" + flag);
	}

	@PostMapping("/editorUpload")
	public JSON editorUpload(MultipartFile file) throws IOException {
		String originalFilename = file.getOriginalFilename();//获取源文件名称
		String flag = IdUtil.fastSimpleUUID();
		//获取上传路径
		String rootFilePath = System.getProperty("user.dir") + "/springboot/src/main/resources/files/" + flag + "-" + originalFilename;
		//写入路径
		FileUtil.writeBytes(file.getBytes(), rootFilePath);
		String url = ip + ":" + port + "/file/" + flag;
		JSONObject json = new JSONObject();
		json.set("errno", 0);
		JSONObject data = new JSONObject();
		data.set("url", url);
		JSONArray jsonArray = new JSONArray();
		jsonArray.add(data);
		json.set("data", jsonArray);
		return json;
	}

	@GetMapping("/{flag}")
	public void getFiles(@PathVariable String flag, HttpServletResponse response) {
		OutputStream os;
		String basePath = System.getProperty("user.dir") + "/springboot/src/main/resources/files/";
		List<String> fileNames = FileUtil.listFileNames(basePath);
		String fileName = fileNames.stream().filter(name -> name.contains(flag)).findAny().orElse("");
		try {
			if (StrUtil.isNotEmpty(fileName)) {
				response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
				response.setContentType("application/octer-stream");
				byte[] bytes = FileUtil.readBytes(basePath + fileName);
				os = response.getOutputStream();
				os.write(bytes);
				os.flush();
				os.close();
			}
		} catch (Exception e) {
			System.out.println("文件下载失败");
		}
	}
}
